import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { toast, showLoading, hideLoading } from "@/utils";

interface formData {
  [key: string]: any;
}

// 初始化表格
export const useInitTable = (options: formData) => {
  // 搜索相关
  const searchForm = reactive({ ...options.searchForm });
  // 重置搜索
  const handleRestSearch = () => {
    for (const key in options.searchForm) {
      searchForm[key] = options.searchForm[key];
    }
    handleGetTableList();
  };

  // 分页
  const currentPage = ref(1);
  const limit = ref(options.limit || 10);
  const total = ref(0);
  // 表格数据
  const tableData = ref([]);
  // loading
  const loading = ref(false);

  // 获取表格数据
  const handleGetTableList = (page: number = 1) => {
    currentPage.value = page;
    tableData.value = [];
    loading.value = true;
    options
      .getTableList({ current: page, pageSize: limit.value, ...searchForm })
      .then((res: any) => {
        // console.log(res);
        if (options.success && typeof options.success == "function") {
          options.success(res);
        } else {
          if (typeof res.length == "number") {
            tableData.value = res;
            total.value = res.length;
          } else {
            tableData.value = res.data;
            total.value = res.total;
          }
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 修改状态
  const handleChangeStatus = (status: boolean, row: any) => {
    row.statusLoading = true;
    options
      .updateStatus(row.id, status)
      .then(() => {
        toast("修改状态成功");
        row.status = status;
      })
      .finally(() => {
        row.statusLoading = false;
      });
  };

  // 删除
  const handleDelete = (row: any) => {
    // 显示 loading 提示
    showLoading();
    options
      .deleteData(row.id)
      .then(() => {
        toast("删除成功");
        handleGetTableList(currentPage.value);
      })
      .finally(() => {
        hideLoading();
      });
  };

  onMounted(() => {
    !options.isNotRefresh && handleGetTableList();
  });

  return {
    searchForm,
    currentPage,
    limit,
    total,
    tableData,
    loading,
    handleRestSearch,
    handleGetTableList,
    handleChangeStatus,
    handleDelete
  };
};

// 初始化 form表单
import type { Ref } from "vue";
export const useInitForm = (options: formData, tableData?: Ref<any[]>) => {
  // 表单部分
  const formDrawerRef = ref<FormInstance>();
  const editId = ref("");
  const drawerTitle = computed(() => (editId.value ? "编辑" : "新增"));
  const form = reactive({}) as any;
  const formRef = ref<FormInstance>();
  const rules = reactive(options.rules || []);

  // 提交表单
  const handleSubmit = () => {
    formRef.value?.validate((valid) => {
      // console.log(valid);
      if (!valid) return;
      (formDrawerRef.value as any).showLoading();
      // 提交之前
      if (options.beforeSubmit && typeof options.beforeSubmit == "function") {
        options.beforeSubmit(form);
      }
      if (!options.isRequest) {
        // 新增或修改
        const fun = editId.value
          ? options.updateData({ id: editId.value, ...form })
          : options.createData(form);
        // 执行提交
        fun
          .then((result: any) => {
            !options.isNotTips && toast(drawerTitle.value + "成功");
            (formDrawerRef.value as any).close();
            if (options.success && typeof options.success == "function") {
              options.success(result);
            }
            //  // 新增数据时，将新数据插入到列表的第一位
            //  if (!editId.value && tableData) {
            //   tableData.value.unshift(result.data);
            // }
          })
          .finally(() => {
            (formDrawerRef.value as any).hideLoading();
          });
      } else {
        (formDrawerRef.value as any).close();
        (formDrawerRef.value as any).hideLoading();
      }
    });
  };

  // 重置表单
  const handleResetFrom = (row = false) => {
    // 清除之前表单的验证状态
    if (formRef.value) formRef.value.clearValidate();
    const defaultForm = row ? row : options.form;
    for (const key in defaultForm) {
      form[key] = defaultForm[key];
    }
  };

  // 新增
  const handleCreate = () => {
    handleResetFrom();
    editId.value = "";
    (formDrawerRef.value as any).open();
  };

  // 修改
  const handleEdit = (row: any) => {
    handleResetFrom(row);
    editId.value = row.id;
    (formDrawerRef.value as any).open();
  };

  return {
    formDrawerRef,
    drawerTitle,
    form,
    formRef,
    rules,
    handleSubmit,
    handleResetFrom,
    handleCreate,
    handleEdit
  };
};
